<template>
  <div>
    <div class="search-bar">
      <!-- 查询条件和新增按钮 -->
      <el-row gutter="20">
        <el-col :span="4">
          <el-select v-model="repairArea" placeholder="请选择维修区域" clearable>
            <el-option
                v-for="item in regionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="userState" placeholder="请选择状态" clearable>
            <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="5" :offset="8">
          <el-button type="primary" @click="openAddDialog">新增维修工人</el-button>
        </el-col>
      </el-row>
    </div>
    <div class="search-bar">
      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="border-card">
        <el-tab-pane label="未删除用户" name="active">
          <!-- 维修工人表格 -->
          <el-table :data="activeWorkers" style="width: 90%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="employeeInfoId" label="编号" width="180"></el-table-column>
            <el-table-column prop="userName" label="姓名" width="180"></el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <span :style="{ color: getColorByState(scope.row.userState) }">
                  {{ getStateText(scope.row.userState) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="expand2" label="区域"></el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                    v-if="scope.row.userState === 0"
                    size="mini"
                    type="warning"
                    @click="disableWorker(scope.row.userId)"
                >
                  禁用
                </el-button>
                <el-button
                    v-if="scope.row.userState === 1"
                    size="mini"
                    type="success"
                    @click="enableWorker(scope.row.userId)"
                >
                  启用
                </el-button>
                <el-button
                    size="mini"
                    type="danger"
                    @click="deleteWorker(scope.row.userId)"
                    :disabled="scope.row.userState === 3"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="已删除用户" name="deleted">
          <!-- 已删除用户表格 -->
          <el-table :data="deletedWorkers" style="width: 90%">
            <el-table-column prop="employeeInfoId" label="编号" width="180"></el-table-column>
            <el-table-column prop="userName" label="姓名" width="180"></el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <span :style="{ color: getColorByState(scope.row.userState) }">
                  {{ getStateText(scope.row.userState) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="expand2" label="区域"></el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 分页组件 -->
    <el-row>
      <el-col :span="16">
        <div class="pagination-container">
          <el-pagination
              :current-page="pageNum"
              :page-size="pageSize"
              :page-sizes="[10, 20, 30]"
              :total="total"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" v-if="activeTab === 'active'" @click="deleteSelectedWorkers">修改区域</el-button>
      </el-col>
    </el-row>
    <!-- 选择区域弹窗 -->
    <el-dialog v-model="areaDialogVisible" width="30%" :before-close="handleCloseAreaDialog">
      <el-form :model="areaForm" :rules="areaRules" ref="areaFormRef">
        <span class="bold-large">修改维修区域</span>
        <el-form-item label="区域" prop="areaCodeId">
          <el-select v-model="areaForm.areaCodeId" placeholder="请选择">
            <el-option v-for="item in regionOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <span>
          <el-button @click="cancelAreaForm">取 消</el-button>
          <el-button type="primary" @click="submitAreaForm">确 定</el-button>
        </span>
      </el-form>
    </el-dialog>

    <!-- 添加维修工人模态框 -->
    <el-dialog v-model="addDialogVisible" width="30%">
      <el-form :model="addForm" :rules="rules" ref="addFormRef">
        <span class="bold-large">添加维修工人</span>

        <el-form-item label="用户名" prop="userName">
          <el-input v-model="addForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="工号" prop="userName">
          <el-input v-model="addForm.userCard"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model="addForm.passWord" type="password"></el-input>
        </el-form-item>
        <el-form-item label="专业" prop="phone">
          <el-input v-model="addForm.profession"></el-input>
        </el-form-item>
        <el-form-item label="维修区域" prop="areaCodeId">
          <el-select v-model="addForm.areaCodeId" placeholder="请选择">
            <el-option v-for="item in regionOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <span>
           <el-button @click="cancelForm('addForm')">取 消</el-button>
          <el-button type="primary" @click="submitForm('addFormRef', false)">确 定</el-button>
        </span>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import {
  ElTable, ElTableColumn, ElForm,
  ElInput, ElButton, ElPagination, ElDialog,
  ElMessage, ElTabs, ElTabPane
} from "element-plus";
import axios from "axios";

export default {
  components: {
    ElTable, ElTableColumn, ElForm,
    ElInput, ElButton, ElPagination, ElDialog,
    ElMessage, ElTabs, ElTabPane
  },
  data() {
    return {
      workers: [],
      total: 0,
      addForm: this.getDefaultForm(),
      repairArea: "",
      pageNum: 1,
      pageSize: 10,
      addDialogVisible: false,
      regionOptions: [],
      selectedWorkers: [],
      rules: {
        userName: [{required: true, message: "请输入姓名", trigger: "blur"}],
        passWord: [{required: true, message: "请输入密码", trigger: "blur"}, {
          min: 1,
          max: 10,
          message: "密码长度在1-10位之间",
          trigger: "blur"
        }],
        phone: [{required: true, message: "请输入手机号", trigger: "blur"}, {
          pattern: /^1[3-9]\d{9}$/,
          message: "手机号格式不正确",
          trigger: "blur"
        }],
        areaCodeId: [{required: true, message: "请选择区域", trigger: "change"}],
      },
      areaDialogVisible: false,
      areaForm: {
        areaCodeId: null,
      },
      areaRules: {
        areaCodeId: [{required: true, message: "请选择区域", trigger: "change"}],
      },
      activeTab: 'active', // 默认显示未删除用户
      activeWorkers: [],
      deletedWorkers: [],
      userState: "", // 用户状态
      state: 0,
      stateOptions: [
        {value: 0, label: '正常'},
        {value: 1, label: '禁用'},
        {value: 3, label: '接单中'},
      ],
    };
  },
  methods: {
    async fetchRegionOptions() {
      try {
        const response = await axios.get("/user/areaCode/listAreaCode");
        if (response.data.code === 200) {
          this.regionOptions = response.data.data.map((area) => ({
            value: area.areaCodeId,
            label: area.areaCodeName
          }));
        } else {
          ElMessage.error("获取区域列表失败");
        }
      } catch (error) {
        ElMessage.error("获取区域列表失败");
        console.error(error);
      }
    },
    async fetchWorkers() {
      try {
        const token = localStorage.getItem("token");
        const searchParams = {
          areaCodeId: "",
          userState: "",
          pageNum: "",
          pageSize: "",
        };
        if (this.state === 0) {
          searchParams.areaCodeId = this.repairArea
          searchParams.userState = this.userState
          searchParams.pageNum = this.pageNum
          searchParams.pageSize = this.pageSize
        } else {
          searchParams.areaCodeId = this.repairArea
          searchParams.userState = this.state
          searchParams.pageNum = this.pageNum
          searchParams.pageSize = this.pageSize
        }

        const response = await axios.post("/user/employeeInfo/queryWorkerList", searchParams, {headers: {token}});

        if (response.data.code === 200) {
          this.workers = response.data.data.list.map(worker => ({
            employeeInfoId: worker.employeeInfoId,
            userId: worker.userId,
            userName: worker.userName,
            profession: worker.profession || "", // 确保 profession 字段存在
            expand2: worker.expand2 || "", // 确保 expand2 字段存在
            userState: worker.userState,
          })).sort((a, b) => a.employeeInfoId - b.employeeInfoId); // 按 employeeInfoId 排序

          this.activeWorkers = this.workers.filter(worker => worker.userState !== 2);
          this.deletedWorkers = this.workers.filter(worker => worker.userState === 2);

          this.total = response.data.data.total;
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error("Error:", error);
        ElMessage.error("获取维修工人列表失败");
      }
    },
    async disableWorker(userId) {
      try {
        const token = localStorage.getItem("token");
        const response = await axios.get(`/user/employeeInfo/disableWorker?userId=${userId}`, {headers: {token}});

        if (response.data.code === 200) {
          this.fetchWorkers();
          ElMessage.success("维修工人禁用成功");
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error("Error:", error);
        ElMessage.error("禁用失败");
      }
    },

    async enableWorker(userId) {
      try {
        const token = localStorage.getItem("token");
        const response = await axios.get(`/user/employeeInfo/enableWorker?userId=${userId}`, {headers: {token}});

        if (response.data.code === 200) {
          this.fetchWorkers();
          ElMessage.success("维修工人启用成功");
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error("Error:", error);
        ElMessage.error("启用失败");
      }
    },

    async deleteWorker(userId) {
      try {
        const token = localStorage.getItem("token");
        const response = await axios.get(`/user/employeeInfo/deleteWorker?userId=${userId}`, {headers: {token}});

        if (response.data.code === 200) {
          this.fetchWorkers();
          ElMessage.success("维修工人删除成功");
        } else {
          ElMessage.error(response.data.msg);
        }
      } catch (error) {
        console.error("Error:", error);
        ElMessage.error("删除失败");
      }
    },

    openAddDialog() {
      this.resetForm("addFormRef");
      this.addDialogVisible = true;
    },

    deleteSelectedWorkers() {
      if (this.selectedWorkers.length === 0) {
        ElMessage.error("请勾选要修改区域的工人");
        return;
      }
      this.areaDialogVisible = true;
    },

    handleSizeChange(size) {
      this.pageSize = size;
      this.pageNum = 1;
      this.fetchWorkers();
    },

    handleCurrentChange(page) {
      this.pageNum = page;
      this.fetchWorkers();
    },

    cancelForm(formName) {
      this.resetForm(formName);
      this[`${formName === 'addForm' ? 'add' : 'edit'}DialogVisible`] = false;
    },

    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
      this[formName] = formName === 'addForm' ? this.getDefaultForm() :null;
    },

    getDefaultForm() {
      return {
        userName: "",
        passWord: "",
        phone: "",
        profession: "",
        userCard:"",
        areaCodeId: null,
        areaCodeInfo: ""
      };
    },


    async submitForm(formName, isEdit) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            const token = localStorage.getItem("token");
            const formData = isEdit ? null : this.addForm;

            const selectedArea = this.regionOptions.find(option => option.value === formData.areaCodeId);
            formData.areaCodeInfo = selectedArea ? selectedArea.label : "";

            const response = await axios.post('/user/employeeInfo/insertEmployee.api',formData, {headers: {token}});

            if (response.data.code === 200) {
              await this.fetchWorkers();
              this.resetForm(formName);
              this[`${isEdit ? 'edit' : 'add'}DialogVisible`] = false;
              ElMessage.success("操作成功");
            } else {
              ElMessage.error(response.data.msg);
            }
          } catch (error) {
            console.error("Error:", error);
            console.error("Error response:", error.response);
            ElMessage.error("操作失败");
          }
        } else {
          console.log("error submit!!");
        }
      });
    },

    handleCloseAreaDialog(done) {
      this.$confirm("确认关闭？")
          .then((_) => {
            this.resetAreaForm();
            done();
          })
          .catch((_) => {
          });
    },

    cancelAreaForm() {
      this.resetAreaForm();
      this.areaDialogVisible = false;
    },

    resetAreaForm() {
      this.areaForm = {
        areaCodeId: null,
      };
    },

    async submitAreaForm() {
      this.$refs.areaFormRef.validate(async (valid) => {
        if (valid) {
          try {
            const token = localStorage.getItem("token");
            const modifyUserId = localStorage.getItem("userId"); // 假设 userId 存储在 localStorage 中

            const updateForms = this.selectedWorkers.map(worker => ({
              employeeInfoId: worker.employeeInfoId,
              areaCodeId: this.areaForm.areaCodeId,
              modifyUserId: modifyUserId
            }));

            const response = await axios.post("/user/employeeInfo/updateWorkerInfo", updateForms, {headers: {token}});

            if (response.data.code === 200) {
              await this.fetchWorkers();
              this.resetAreaForm();
              this.areaDialogVisible = false;
              ElMessage.success("修改成功");
            } else {
              ElMessage.error(response.data.msg);
            }
          } catch (error) {
            console.error("Error:", error);
            ElMessage.error("修改失败");
          }
        } else {
          console.log("error submit!!");
        }
      });
    },

    handleSelectionChange(selection) {
      this.selectedWorkers = selection;
    },

    handleTabClick({props}) {
      if (props.name === 'active') {
        this.state = 0;
        this.userState = ''; // 清空状态以获取所有状态的未删除用户
      } else if (props.name === 'deleted') {
        this.state = 2; // 设置状态为2以获取已删除用户
      }
      this.fetchWorkers();
    },

    getStateText(state) {
      switch (state) {
        case 0:
          return '正常';
        case 1:
          return '禁用';
        case 2:
          return '删除';
        case 3:
          return '接单中';
        default:
          return '未知状态';
      }
    },

    getColorByState(state) {
      switch (state) {
        case 0:
          return 'green';
        case 1:
          return 'red';
        case 2:
          return 'gray';
        case 3:
          return 'blue'; // 你可以根据需要选择合适的颜色
        default:
          return 'black';
      }
    },
  },

  watch: {
    repairArea: 'fetchWorkers',
    userState: 'fetchWorkers'
  },

  created() {
    this.fetchWorkers();
    this.fetchRegionOptions();
  },
};
</script>

<style scoped>
.search-bar {
  width: 100%;
  margin-bottom: 15px;
}

.bold-large {
  font-weight: bold;
  font-size: 1.5em; /* 调整字体大小，可以根据需要调整 */
}

.pagination-container {
  margin-top: 20px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
}
</style>
